<template>
    <div class="app-container">
        <div v-show="!addedShow && !detailsShow">
            <el-form
                :model="queryParams"
                ref="queryForm"
                :inline="true"
                v-show="showSearch"
                label-width="68px"
            >
                <el-form-item label="业务部门" prop="officeId">
                    <el-cascader
                        placeholder="可输入关键字搜索"
                        :options="dept"
                        clearable
                        v-model="queryParams.officeId"
                        :show-all-levels="false"
                        :props="{ value: 'id',checkStrictly: true,emitPath:false,leaf : 'leaf' }"
                        filterable
                    ></el-cascader>
                </el-form-item>
                <el-form-item label="系统名称" prop="projectName">
                    <el-input
                        v-model="queryParams.projectName"
                        placeholder="请输入系统名称"
                        clearable
                        size="small"
                        @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button
                        type="cyan"
                        icon="el-icon-search"
                        size="mini"
                        @click="handleQuery"
                        >搜索</el-button
                    >
                    <el-button
                        icon="el-icon-refresh"
                        size="mini"
                        @click="resetQuery"
                        >重置</el-button
                    >
                </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button
                        type="primary"
                        icon="el-icon-plus"
                        size="mini"
                        @click="showAdd"
                    >
                        申请</el-button
                    >
                </el-col>
                <right-toolbar
                    :showSearch.sync="showSearch"
                    @queryTable="getList"
                ></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="demoList" style="width: 100%">
                <el-table-column label="系统名称" prop="projectName" />
                <el-table-column label="业务部门" prop="officeName" />
                <el-table-column label="云服务商" prop="cloudSupplierName" />
                <el-table-column label="状态" prop="bpmStatus" />
                <el-table-column label="发起人" prop="createByName" />
                <el-table-column label="申请时间" prop="createTime" />
                <el-table-column label="更新时间" prop="updateTime" />
                <el-table-column
                    label="操作"
                    class-name="small-padding fixed-width"
                >
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-search"
                            @click="showDetail(scope.row.id)"
                            >详情</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>

            <pagination
                v-show="total > 0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
            />
        </div>
    </div>
</template>

<script>
import ApplyBefore from "@/components/Activiti/ApplyBefore/index";
import ApplyAfter from "@/components/Activiti/ApplyAfter/index";
import Details from "./details.vue";
import Examine from "./examine.vue";
import AddA from "./addA.vue";
import AddB from "./addB.vue";
import AddC from "./addC.vue";
import Process from "../../todoItem/todo/process.vue";
import {
    listDemo,
    getDemo,
    delDemo,
    addDemo,
    updateDemo,
    exportDemo,
} from "@/api/example/demo";
import { listUser } from "@/api/system/user";
import {
    resourcesUpList,
    resourcesUpDetail,
    apply,
    listByCode,
    serviceByClazz,
} from "@/api/resources/apply";
import { treeselect } from "@/api/system/dept";
import { getDicts } from "@/api/system/dict/data";
import { addCloudUp } from "@/api/cloud/cloud";
import { uploadFile } from "@/api/system/upload.js";
import request from "@/utils/request";

export default {
    name: "list",
    components: {
        ApplyBefore,
        ApplyAfter,
        Details,
        Examine,
        AddA,
        AddB,
        AddC,
        Process,
    },
    data() {
        return {
            btnLoading: false,
            addBFlag: false,
            // 遮罩层
            loading: false,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 示例Demo表格数据
            demoList: [],
            // 弹出层标题
            title: "",
            // 是否显示详情
            detailsShow: false,
            // 详情
            detail: false,
            // 是否显示申请
            addedShow: false,
            // 申请步骤
            active: 0,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                officeId: null,
                projectName: null,
                status: "",
            },
            //配置
            configure: {
                available_domain: [], //可用域
                cloud_service_provider: [], //服务商
                storage_type: [], //系统盘类型
                codeList: [], //云服务器规格列表
                czxtList: [], //操作系统列表
                ccList: [], //数据盘类型
                fwcpList: [], //服务型磁盘类型
                wlfwqList: [], //高性能服务器资源类型
                sjkList: [], //数据库类型
                yyaqList: [], //安全产品
            },
            // 表单参数
            form: {
                //系统id
                cloudUpId: "",
                //系统基本信息
                cloudUp: {},
                cloudSupplier: "", //服务商
                cloudSupplier_label: "", //服务商名称
                hosts: [], //资源列表
                databases: [], //数据库列表
                storeProducts: [], //存储产品列表
                safeProducts: [], //安全产品列表
                remark: "", //说明
                files: [], //文件
            },
            // 表单校验
            rules: {},
            //部门列表树结构
            dept: [],
        };
    },
    watch: {
        $route(route) {
          if(route.fullPath == '/resources/apply'){
              this.getList();
          }
        },
    },
    created() {
        this.getListDept();
        this.getList();
        this.getDataOfAdd();
    },
    methods: {
        //查看详情
        showDetail(id) {
            this.$router.push("/resources/applys/Detailsindex/" + id);
            return;
            resourcesUpDetail(id).then((res) => {
                let detail = res.data;
                detail.storeProducts.forEach((data) => {
                    this.configure[
                        data.productCode == "共享型" ? "ccList" : "fwcpList"
                    ].some((it) => {
                        if (it.code == data.diskServerCode) {
                            data.diskServerCode_label = it.serviceName;
                            return true;
                        }
                    });
                    data.hostInstanceNames = [];
                    if (data.hosts) {
                        data.hosts.forEach((item) => {
                            data.hostInstanceNames.push(item.instanceName);
                        });
                    }
                });
                detail.databases.forEach((data) => {
                    this.configure.sjkList.some((it) => {
                        if (it.code == data.serverCode) {
                            data.serverCode_label = it.serviceName;
                            return true;
                        }
                    });
                });
                detail.hosts.forEach((data) => {
                    data.hostName = data.instanceName;
                    //可用域
                    this.configure.available_domain.some((item) => {
                        if (item.dictValue == data.availableDomain) {
                            data.availableDomain_label = item.dictLabel;
                            return true;
                        }
                    });
                    //系统盘类型
                    if (data.osDisk) {
                        this.configure.storage_type.some((item) => {
                            if (item.code == data.osDisk.diskServerCode) {
                                data.osDisk.diskServerCode_label =
                                    item.serviceName;
                                return true;
                            }
                        });
                    }
                    //数据盘类型
                    if (data.disks) {
                        data.disks.forEach((item) => {
                            this.configure.ccList.some((it) => {
                                if (it.code == item.diskServerCode) {
                                    item.diskServerCode_label = it.serviceName;
                                    return true;
                                }
                            });
                        });
                    } else {
                        data.disks = [];
                    }
                    //规格
                    if (data.flavorType == 1) {
                        this.configure.codeList.some((item) => {
                            if (item.specCode == data.cloudFlavorCode) {
                                data.cloudFlavorCode_label = item.specName;
                                data.cloudFlavorCode_desc = item.desc;
                                return true;
                            }
                        });
                    }
                    if (data.flavorType == 2) {
                        this.configure.wlfwqList.some((item) => {
                            if (item.code == data.cloudFlavorCode) {
                                data.cloudFlavorCode_label = item.serviceName;
                                data.cloudFlavorCode_desc = item.remark;
                                return true;
                            }
                        });
                    }
                });
                this.detail = detail;
                this.detailsShow = true;
            });
        },
        //部门列表
        getListDept() {
            treeselect({}).then((response) => {
                this.dept = response.data;
            });
        },
        //生成树结构
        generateOptions(params) {
            //生成Cascader级联数据
            var result = [];
            for (let param of params) {
                if (param.parentId == 0) {
                    //判断是否为顶层节点
                    var parent = {
                        //转换成el-Cascader可以识别的数据结构
                        label: param.deptName,
                        value: param.deptId,
                    };
                    parent.children = this.getchilds(param.deptId, params); //获取子节点
                    result.push(parent);
                }
            }
            return result;
        },
        getchilds(id, array) {
            let childs = new Array();
            for (let arr of array) {
                //循环获取子节点
                if (arr.parentId == id) {
                    childs.push({
                        label: arr.deptName,
                        value: arr.deptId,
                    });
                }
            }
            for (let child of childs) {
                //获取子节点的子节点
                let childscopy = this.getchilds(child.value, array); //递归获取子节点
                if (childscopy.length > 0) {
                    child.children = childscopy;
                }
            }
            return childs;
        },
        //下一步
        next(data) {
            if (data) {
                if (this.active == 1) {
                    if (data.cloudUpId) {
                        this.form.cloudUpId = data.cloudUpId;
                    } else {
                        this.form.cloudUpId = "";
                        data.fundBySelf = data.fundBySelf == "1" ? true : false;
                        if (data.fundFromRadio == "1") {
                            data.fundFrom = "区（县）";
                        } else if (data.fundFromRadio == "2") {
                            data.fundFrom = "市级";
                        }
                    }
                    this.form.cloudUp = data;
                } else if (this.active == 2) {
                    this.form.cloudSupplier = data.cloudSupplier;
                    this.form.cloudSupplier_label = data.cloudSupplier_label;
                    this.form.hosts = data.hosts;
                    this.form.databases = data.databases;
                    this.form.storeProducts = data.storeProducts;
                    this.form.safeProducts = data.safeProducts;
                    this.form.remark = data.remark;
                    this.form.files = data.fileList;
                }
                this.active++;
            } else if (this.active == 1) {
                this.$refs.adda.next();
            } else if (this.active == 2) {
                this.$refs.addb.next();
            } else {
                this.submitApply();
            }
        },
        /** 提交申请 */
        submitApply() {
            this.$confirm("是否确认提交?", "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                this.btnLoading = true;
                let form = JSON.parse(JSON.stringify(this.form));
                if (this.form.files && this.form.files.length) {
                    let param = new FormData();
                    param.append("key", "file");
                    this.form.files.forEach((item) => {
                        param.append("file", item.raw);
                    });
                    uploadFile(param)
                        .then((res) => {
                            form.files = res.data;
                            this.sub(form);
                        })
                        .catch((e) => {
                            this.btnLoading = false;
                        });
                } else {
                    this.sub(form);
                }
            });
        },
        sub(form) {
            form.hosts.forEach((item) => {
                item.instanceName = item.hostName;
                item.osServerCode =
                    item.osServerCode[item.osServerCode.length - 1];
            });
            form.officeId = form.cloudUp.officeId;
            if (!form.cloudUpId) {
                addCloudUp(form.cloudUp).then((re) => {
                    form.cloudUpId = re.data.id;
                    delete form.cloudUp;
                    apply({ formObject: form })
                        .then((res) => {
                            this.$message({
                                message: "提交成功",
                                type: "success",
                            });
                            this.addedShow = false;
                            this.getList();
                        })
                        .finally(() => {
                            this.btnLoading = false;
                        });
                });
            } else {
                delete form.cloudUp;
                apply({ formObject: form })
                    .then((res) => {
                        this.$message({
                            message: "提交成功",
                            type: "success",
                        });
                        this.addedShow = false;
                        this.getList();
                    })
                    .finally(() => {
                        this.btnLoading = false;
                    });
            }
        },
        //申请弹窗
        showAdd() {
            this.$router.push("/resources/applys/addapply");
            return;
            this.addedShow = true;
            this.active = 1;
            setTimeout(() => {
                this.$refs.process.init({
                    definitionName: "资源申请",
                    taskName: "资源申请",
                });
            }, 100);
        },
        //获取一些配置数据
        getDataOfAdd() {
            setTimeout(() => {
                this.addBFlag = true;
            }, 2000);
            //可用域
            getDicts("available_domain").then((response) => {
                this.configure.available_domain = response.data;
            });
            //服务商
            getDicts("cloud_service_provider").then((response) => {
                this.configure.cloud_service_provider = response.data;
            });
            //盘类型
            serviceByClazz({ code: "cc" }).then((response) => {
                response.data.forEach((item) => {
                    if (
                        ["FCcc(tykcc)2", "FCcc_ssd", "spycc2"].indexOf(
                            item.code
                        ) < 0
                    ) {
                        this.configure.storage_type.push(item);
                    }
                    if (["spycc2"].indexOf(item.code) < 0) {
                        this.configure.ccList.push(item);
                    }
                    if (
                        ["fbscc_wjcc2", "FCcc(tykcc)2", "FCcc_ssd"].indexOf(
                            item.code
                        ) < 0
                    ) {
                        this.configure.fwcpList.push(item);
                    }
                });
            });
            //操作系统
            serviceByClazz({ code: "czxt" }).then((response) => {
                this.configure.czxtList = response.data;
            });
            //云服务器规格列表
            listByCode("spec_ecs").then((response) => {
                this.configure.codeList = response.data;
            });
            //高性能服务器资源类型列表
            serviceByClazz({ code: "wlfwq" }).then((response) => {
                this.configure.wlfwqList = response.data;
            });
            //数据库类型列表
            serviceByClazz({ code: "sjk" }).then((response) => {
                this.configure.sjkList = response.data;
            });
            //安全产品列表
            serviceByClazz({ code: "yyaq" }).then((response) => {
                this.configure.yyaqList = response.data;
            });
        },
        /** 查询列表 */
        getList() {
            this.loading = true;
            resourcesUpList(this.queryParams)
                .then((response) => {
                    this.demoList = response.rows;
                    this.total = response.total;
                    this.loading = false;
                })
                .then(() => {});
        },
        handleQuery() {
            this.getList()
        },
        resetQuery() {
            this.queryParams.officeId = null
            this.queryParams.projectName = ''
            this.getList()
        },
    },
};
</script>
<style lang="scss" scoped>
    .el-table{
        color: #000;
    }
.el-step__description {
    margin: 5px 0 14px 0 !important;
}
</style>
